package com.xingda.packing.task.listener;

import com.xingda.packing.domain.PackProductionLine;
import com.xingda.packing.domain.ProductBoxLocation;
import com.xingda.packing.domain.Wheel;
import com.xingda.packing.enums.TaskState;
import com.xingda.packing.enums.TaskType;
import com.xingda.packing.task.ticket.CachePackingTicket;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.Optional;

@Slf4j
@Component
public class CachePackingListener implements TaskListenerService {
    @Override
    public boolean accept(PackProductionLine productionLine, int area) {
        return checkTask(productionLine.getRobot().getTaskTicket(area), TaskType.CACHE_PALLETIZING);
    }

    @Override
    public void monitor(PackProductionLine productionLine, int area) {
        CachePackingTicket ticket = (CachePackingTicket) productionLine.getRobot().getTaskTicket(area);
        if (productionLine.getRobot().isGrabComplete(area)) {
            productionLine.getRobot().resetGrabState(area);
        }
        if (productionLine.getRobot().isPalletizingComplete(area)) {
            Wheel wheel = ticket.getWheel();
            productionLine.getCacheArea().takeOutWheel(ticket.getCacheLocationNo(), area);
            int boxLocationNo = ticket.getTag();
            Optional<ProductBoxLocation> pblOptional = productionLine.getProductArea().getProductBoxLocation(boxLocationNo);
            if (pblOptional.isPresent() && Objects.nonNull(pblOptional.get().getBox())) {
                pblOptional.get().getBox().putWheel(wheel);
                pblOptional.get().triggerFullAlarm(area);
            }
            ticket.setState(TaskState.FINISH);
            // 缓存位放入装箱位完成动作
            productionLine.getRobot().listenerCachePackingEvent(ticket, area);
        }
    }
}
